# This file is used to create a singleton class for database connection and cursor.
'''settings.py
# POSTGRES
DATABASE_NAME = "anhuning"
DATABASE_USER = "postgres"
DATABASE_PSWD = "123456"
DATABASE_HOST = "localhost"
DATABASE_PORT = 5432
'''
import psycopg2
import psycopg2.pool
import psycopg2.extras
from settings import *
import logging
import os

logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)

class PostgreSingleton:
    
    def __enter__(self):

        conn = psycopg2.connect(
            host=DATABASE_HOST,
            database=DATABASE_NAME,
            user=DATABASE_USER,
            password=DATABASE_PSWD,
            port=DATABASE_PORT
        )
        conn.autocommit = True
        self.conn = conn
        return conn

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            logger.error("Error occurred in PostgreSingleton")
            logger.error(exc_type, exc_val, exc_tb)
        else:
            self.conn.commit()
            self.conn.close()


if __name__ == "__main__":

    #调用示例

    with PostgreSingleton() as conn:
        with conn.cursor() as cur:
            cur.execute("select * from cabinet where mac=%s", ("620790426a0e",))  # 执行 SQL 查询
            rows = cur.fetchone()  # 检索查询结果

    logger.info(rows)